package com.ruoyi.integration.mqtt.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @Description : mqtt配置
 * @Author : Bruce Lee
 * @CreateTime : 2025/2/17
 */

@Slf4j
@Configuration
public class MqttConfig {

    @Autowired
    private MqttProfile profile;

    public MqttClient mqttClient;

    /**
     * 客户端连接
     */
    @PostConstruct
    public void connect() throws MqttException {
        mqttClient = new MqttClient(profile.getHost(), profile.getClientId(), new MemoryPersistence());

        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setConnectionTimeout(profile.getTimeout());
        options.setKeepAliveInterval(profile.getKeepalive());
        // 设置遗嘱消息
//        options.setWill("willTopic", "will msg".getBytes(), 2, true);
        // 设置消息回调
        mqttClient.setCallback(new CustomMqttCallback());
        mqttClient.connect(options);
        log.info("MQTT 客户端连接成功");
    }

}
